package icu.lookyousmileface.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author shenj
 * @title: NettyServer
 * @projectName NettyPro
 * @date 2020/12/3 16:27
 */
public class NettyServer {

    public static void main(String[] args) throws Exception {

        //轮询组,可以指定使用多少内核默认是内核*2
        EventLoopGroup bossEventLoop = new NioEventLoopGroup();
        EventLoopGroup workerEventLoop = new NioEventLoopGroup();
        try{
        //创建Server startApplicationConfiguration对象
        ServerBootstrap startApplicationConfiguration = new ServerBootstrap();

        //线程组
        startApplicationConfiguration.group(bossEventLoop, workerEventLoop)
                //通道选择NioServerSocketChannel作为通道的实现
                .channel(NioServerSocketChannel.class)
                //队列连接个数
                .option(ChannelOption.SO_BACKLOG,128)
                //保持活动连接状态
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                //创建一个匿名的通道测试对
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    //pipeline设置处理器
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyHandler());
                    }
                });
        System.out.println("Server is ready....");
        //绑定服务器端口并同步，sync表示同步，且开启服务器，生成channelFuture对象
        ChannelFuture channelFuture = startApplicationConfiguration.bind(6668).sync();

        //对通道关闭进行监听，并且同步
        channelFuture.channel().closeFuture().sync();
        }finally {
            //出现异常，优雅的关闭
            bossEventLoop.shutdownGracefully();
            workerEventLoop.shutdownGracefully();
        }
    }
}
